<template>
  <div v-loading="loading">
    <StatisticsTableSearch
      ref="StatisticsTableSearch"
      :search-path="searchPath"
      :formItemsInline="formItemsInline"
      :tableBtns="tableBtns"
      :form="form"
      @reset="reset"
      :columns="columns"
      :tableData="tableData"
      @handleTableData="handleTableData"
    >
      <template slot="middle">
        <div style="overflow: auto; margin: 40px 0 20px 0">
          <DataCard :data="dataCard" :items="dataCardItems" :SubMch="true" />
        </div>
      </template>
      <template slot="date">
        <el-form-item>
          <SearchDatePicker
            :start.sync="form.startTime"
            :end.sync="form.endTime"
          />
        </el-form-item>
      </template>
      <template slot="address">
        <el-form-item>
          <HycAddressCascader
            ref="area"
            v-model="form.area"
            :clearable="true"
          />
        </el-form-item>
      </template>
      <template slot="merchant" v-if="form.containSubMch">
        <el-form-item>
          <!-- <el-autocomplete
            style="width: 100%"
            placeholder="请输入代理商名称"
            v-model="selectMerchant"
            :fetch-suggestions="handleQueryMerchant"
            @select="handleSelect"
          /> -->
          <SearchMerchants v-model="form.mchUserId" :defaultOptions="false" />
        </el-form-item>
      </template>
      <template slot="showSub">
        <el-form-item>
          <el-checkbox v-model="form.containSubMch"> 下级代理数据 </el-checkbox>
        </el-form-item>
      </template>
    </StatisticsTableSearch>
  </div>
</template>
<script>
import { selectSubMerchant } from '@/api/common'
import dayjs from 'dayjs'
import Big from 'big.js'
import {
  statisticalReport,
  statisticalReportExcel,
  statisticalReportTotal,
} from '@/api/statisticsForm'
import StatisticsTableSearch from '@/components/StatisticsTableSearch'
import HycAddressCascader from '@/components/hycAddressCascader'
import SearchMerchants from '@/components/SearchMerchants'
import DataCard from './components/DataCard'
export default {
  name: 'statisticsForm',
  components: {
    StatisticsTableSearch,
    HycAddressCascader,
    DataCard,
    SearchMerchants,
  },
  data() {
    return {
      selectMerchant: '',
      tableData: {},
      searchPath: '/web/data-statistic/statistical-report/查询',
      // tableLoading: false,
      // countLoading: false,
      loading: false,
      tableBtns: [
        {
          label: '导出',
          isExport: true,
          startDownload: (callback) => {
            let params = Object.assign(
              {},
              this.form,
              { pageSize: 10, currentPage: 1 },
              this.form.area &&
                this.form.area.province && {
                  province: this.form.area.province,
                },
              this.form.area &&
                this.form.area.city && {
                  city: this.form.area.city,
                },
              this.form.area &&
                this.form.area.district && {
                  district: this.form.area.district,
                }
            )
            params.area && delete params.area
            statisticalReportExcel(params)
              .then((res) => {
                callback(res)
              })
              .catch((err) => {
                console.log(err)
                callback(0)
              })
          },
          resourceId: '/web/data-statistic/statistical-report/导出',
        },
      ],
      dataCard: {
        chargeSum: 0,
        electricitySum: 0,
        durationSum: 0,
        totalRevenue: 0,
        totalCost: 0,
        totalIncome: 0,
      },
      errorOrderReason: '异常订单原因',
      tips: [],
      dataCardItems: [
        {
          label: '充电次数',
          unit: '次',
          formatter: (data) => {
            return Number(data.chargeSum).toLocaleString('zh-CN', {
              maximumFractionDigits: 2, // 最多显示两位小数
            })
          },
        },
        {
          label: '充电电量',
          unit: '度',
          formatter: (data) => {
            return Number(data.electricitySum).toLocaleString('zh-CN', {
              maximumFractionDigits: 2, // 最多显示两位小数
            })
          },
        },
        {
          label: '充电时长',
          unit: '分',
          formatter: (data) => {
            return Number(data.durationSum).toLocaleString('zh-CN', {
              maximumFractionDigits: 2, // 最多显示两位小数
            })
          },
        },
        {
          label: '总收入',
          unit: '元',
          formatter: (data) => {
            return Number(data.totalRevenue).toLocaleString('zh-CN', {
              maximumFractionDigits: 2, // 最多显示两位小数
            })
          },
        },
        {
          label: '总成本',
          unit: '元',
          formatter: (data) => {
            return Number(data.totalCost).toLocaleString('zh-CN', {
              maximumFractionDigits: 2, // 最多显示两位小数
            })
          },
        },
        {
          label: '总利润',
          unit: '元',
          formatter: (data) => {
            return Number(data.totalIncome).toLocaleString('zh-CN', {
              maximumFractionDigits: 2, // 最多显示两位小数
            })
          },
        },
        // {
        //   label: '时长卡订单数',
        //   unit: '元',
        //   formatter: (data) => {
        //     return '-'
        //   }
        // },
        // {
        //   label: '时长卡订单收入',
        //   unit: '元',
        //   formatter: (data) => {
        //     return '-'
        //   }
        // }
      ],
      formItemsInline: [
        {
          slot: 'date',
        },
        {
          slot: 'address',
        },
        // {
        //   placeholder: '请输入代理商名称',
        //   type: 'text',
        //   clearable: true,
        //   value: 'operatorName',
        //   // resourceId: '',
        // },
        {
          slot: 'merchant',
        },
        {
          placeholder: '请输入充电站名称',
          type: 'text',
          clearable: true,
          value: 'stationName',
        },
        {
          slot: 'subMerchant',
        },
        // {
        //   slot: 'showSub',
        // },
      ],
      form: {
        containSubMch: true, //todo
        mchUserId: '',
        startTime: new Date().valueOf() - 7 * 24 * 3600 * 1000,
        endTime: new Date().valueOf(),
      },
      columns: [
        {
          label: '日期',
          prop: 'statistics_date',
          formatter: (row) => {
            return dayjs(row.statistics_date).format('YYYY-MM-DD')
          },
          resourceId: '/web/data-statistic/statistical-report/日期',
          minWidth: 120,
        },
        {
          label: '电站名称',
          prop: 'station_name',
          resourceId: '/web/data-statistic/statistical-report/电站名称',
          minWidth: 120,
        },
        {
          label: '城市',
          prop: 'city',
          resourceId: '/web/data-statistic/statistical-report/城市',
          minWidth: 120,
        },
        {
          label: '所属用户',
          prop: 'operator_name',
          resourceId: '/web/data-statistic/statistical-report/所属用户',
          minWidth: 120,
        },
        {
          label: '插口数',
          prop: 'plug_num',
          resourceId: '/web/data-statistic/statistical-report/插口数',
          minWidth: 120,
        },
        {
          label: '充电次数',
          prop: 'charge_sum',
          resourceId: '/web/data-statistic/statistical-report/充电次数',
          minWidth: 120,
        },
        {
          label: '充电时长(h)',
          prop: 'duration_sum',
          resourceId: '/web/data-statistic/statistical-report/充电时长(h)',
          formatter: (item) => {
            return this.minToHour(item.duration_sum)
          },
          minWidth: 120,
        },
        {
          label: '单口时长(h)',
          prop: 'averageDuration',
          resourceId: '/web/data-statistic/statistical-report/单口时长(h)',
          formatter: (item) => {
            return this.minToHour(item.averageDuration)
          },
          minWidth: 120,
        },
        {
          label: '充电电量',
          prop: 'electricity_sum',
          resourceId: '/web/data-statistic/statistical-report/充电电量',
          minWidth: 120,
        },
        {
          label: '电费成本',
          prop: 'electricity_cost',
          resourceId: '/web/data-statistic/statistical-report/电费成本',
          minWidth: 120,
        },
        {
          label: '时长卡订单数',
          prop: 'timeCardCount',
          resourceId: '/web/data-statistic/statistical-report/时长卡订单数',
          minWidth: 120,
        },
        {
          label: '时长卡收入（元）',
          prop: 'timeCardSum',
          resourceId: '/web/data-statistic/statistical-report/时长卡收入',
          minWidth: 160,
        },
        {
          label: '和能量订单数',
          prop: 'andEnergyCount',
          resourceId: '/web/data-statistic/statistical-report/和能量订单数',
          minWidth: 120,
        },
        {
          label: '和能量收入（元）',
          prop: 'andEnergySum',
          resourceId: '/web/data-statistic/statistical-report/和能量收入',
          minWidth: 160,
        },
        {
          label: '临充收入（元）',
          prop: 'consumption_sum',
          resourceId: '/web/data-statistic/statistical-report/临充收入',
          minWidth: 120,
        },
        {
          label: '服务费收入（元）',
          prop: 'serviceSum',
          resourceId: '/web/data-statistic/statistical-report/服务费收入',
          minWidth: 120,
        },
        {
          label: '电站收益（元）',
          prop: 'totalIncome',
          resourceId: '/web/data-statistic/statistical-report/电站收益',
          minWidth: 120,
        },
        {
          label: '单口收益（元）',
          prop: 'average_income',
          resourceId: '/web/data-statistic/statistical-report/单口收益',
          minWidth: 120,
        },
      ],
    }
  },
  mounted() {},
  watch: {
    'form.containSubMch': {
      handler(val) {
        if (!val) {
          this.form.mchUserId = ''
          this.selectMerchant = ''
        }
      },
    },
  },
  methods: {
    minToHour(minutes) {
      Big.DP = 2
      return parseFloat(Big(minutes).div(60))
    },
    handleSelect(val) {
      this.form.mchUserId = val.id
    },
    async handleQueryMerchant(qs, cb) {
      selectSubMerchant({
        userName: qs,
      })
        .then((res) => {
          if (this.timeout) clearTimeout(this.timeout)

          if (!Array.isArray(res)) return

          let list = res.map((item) => {
            return {
              value: item.name,
              id: item.id,
            }
          })
          this.timeout = setTimeout(() => {
            cb(list)
          }, 1000)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    async handleTableData(params) {
      if (params.area && params.area.province)
        params.province = params.area.province
      if (params.area && params.area.city) params.city = params.area.city
      if (params.area && params.area.district)
        params.district = params.area.district

      delete params.area
      try {
        this.loading = true
        let res = await statisticalReport(params)
        let cardRes = await statisticalReportTotal(params)
        this.tableData = {
          list: res.list,
          totalCount: res.totalAmount,
        }
        this.dataCard = cardRes
        this.loading = false
      } catch (err) {
        console.log(err)
      }
    },
    reset() {
      this.form = {
        containSubMch: true,
        startTime: new Date().valueOf() - 7 * 24 * 3600 * 1000,
        endTime: new Date().valueOf(),
      }
      this.$refs.area.$data.innerValue = []
    },
  },
}
</script>
